import store from "@/store";
import { MessageBox } from "element-ui";
import router from "@/router";
let { NODE_ENV } = process.env;
/**
 * 改变数组对象里面的某些key的值
 * @param data {array}
 * @param changeFileds {array} | "all"
 * @param fieldProp {object} :{field:"prop",key:"",value:""}
 * @return data {array}
 */
export function dataPropHandle(data, changeFileds, fieldProp) {
  data &&
    data.forEach((item) => {
      if (typeof changeFileds === "string") {
        if (changeFileds === "all") {
          item[fieldProp.key] = fieldProp.value;
        } else if (changeFileds == (item[fieldProp?.field] || item.prop)) {
          item[fieldProp.key] = fieldProp.value;
        }
      } else if (changeFileds.includes(item.prop || item[fieldProp?.field])) {
        item[fieldProp.key] = fieldProp.value;
      }
    });
  return data;
}
/**
 * 根据字段分类和字典值，获取字典label
 * @param {number | array} dicType
 * @param {string} dicVal
 * @param {string} propName 匹配哪个字段
 * @returns
 */
//获取字典匹配的label值
export function getDicLabel(dicType, dicVal, propName) {
  let dicData = [];
  if (Array.isArray(dicType)) {
    dicData = dicType.filter((item) => {
      return (item[propName] || item.value) == dicVal;
    });
  } else {
    dicData = store.state.dictionary[dicType].filter((item) => {
      return (item[propName] || item.value) == dicVal;
    });
  }
  return (dicData.length > 0 && dicData[0].label) || "";
}
/**
 *
 * @param {object}
 * @param {function} 回调函数
 *
 */
export function $confirm(params, callback) {
  let { content, title, confirmButtonText, cancelButtonText, type } = params;
  MessageBox.confirm(content || "此操作将永久删除, 是否继续?", title || "提示", {
    confirmButtonText: confirmButtonText || "确定",
    cancelButtonText: cancelButtonText || "取消",
    type: type || "warning",
  })
    .then(() => {
      arguments.length == 1 ? params() : callback(); //如果参数是一个，直接执行回调函数
    })
    .catch(() => {});
}
/**
 *处理打来新窗口逻辑
 * @param {params} 路由动态地址
 * @param {target} 回调函数
 *
 */
export function $router(params, target) {
  if (target === "_blank") {
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    router.push(params);
  }
}
//节流
export function throttle(fn, delay) {
  let valid = true;
  return function () {
    if (!valid) {
      //休息时间 暂不接客
      return false;
    }
    // 工作时间，执行函数并且在间隔期内把状态位设为无效
    valid = false;
    setTimeout(() => {
      fn();
      valid = true;
    }, delay);
  };
}
/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}
export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

// 创建一个uuid
export function uuid(length = 8, chars) {
  let result = "";
  let charsString = chars || "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (let i = length; i > 0; --i) {
    result += charsString[Math.floor(Math.random() * charsString.length)];
  }
  return result;
}

export function isObject(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

//iconfont编码转换
// {
//   name: '首页',
//   icon: '&#xe747;',
// },
export function iconfont(icon) {
  const reg = /(&#x)?(.*)/;
  let iconfontName;
  if (reg.test(icon)) {
    iconfontName = reg.exec(icon)[2];
  }
  console.log(icon);
  return String.fromCharCode(parseInt(iconfontName, 16));
}

export function isMobile() {
  //手机端
  return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? true : false;
}
